<?php
namespace Home\Controller;
use Think\Controller;
use Org\Util\Curl;

class IndexController extends Controller {
    
    
    protected $prefix;         //数据标记前缀
    protected $db_table;         //打卡记录表的表名
    protected $db_field;         //打卡记录表的时间字段
    protected $dev_name;
    
    protected $act_config = 'config';    //配置信息对应的方法
    protected $act_send = 'send';        //传输数据对应的接口方法
    protected $url = '';
    protected $domain = 'web.idea.3xy.me';
    protected $api_user = 'http://insightaccount.idea.3xy.me/';
    
    public function _initialize(){
        
        $this->prefix = C('DEV_CODE');
        $this->db_table = C('DB_CHECKIN');
        $this->db_field = C('DB_CHECKIN_TIME');
        
        $this->model = D($this->db_table);
        
        if (APP_STATUS =='local'){
            $this->domain = 'localhost';
            $this->api_user ='http://localhost/insight_account2016/';
            
        }
        $this->domain = APP_STATUS =='local' ? 'localhost' : 'web.idea.3xy.me';
        $this->url = "http://$this->domain/insight20170117_attendance/index.php?g=&m=loader&a=";
    }
    
    
    /**
     * 修复功能：检查数据总量
     * 检查前一天的打卡数据是否和阿里云的打卡记录一致
     * 部署使用的时候要检查：
     * 1.数据库是否正确，
     * 2.表是否正确
     * 3. APP_STAUS是否正确
     * 4.检查$prefix是否正确
     * date:2017年9月20日
     * author: EK_熊
     */
    public function check_total($day=''){
        $url_check = $this->url.'total_prev';//检查打卡记录总数量接口方法
        $url_check_result = $this->url.'total_prev_result';
        
        $day = $day ? $day : date('Y-m-d',(time()-86400));
        
        
        $map['_string']="{$this->db_field} >= '$day 00:00:00' AND {$this->db_field} <= '$day 23:59:59'";
        $count = $this->model->where($map)->count();
        
        //获取阿里云的打卡记录数据
        $curl = new Curl();
        $str = $curl->post($url_check,['day'=>$day]);
        $request = json_decode(trim($str,chr(239).chr(187).chr(191)),true);
        
        if ($request) {
            $intval = intval($count) - intval($request['count']);
            $msg = "数据正常";
            $code = 0;
            if ($intval > 0){
              $msg = "打卡记录相差了{$intval}条";
              $code = 1;
              $this->send_msg($day, $msg,$code);
              $this->dump("发现{$intval}条遗漏数据,开始进行修复......");
              //出现数据异常，进行数据修复
              $this->check_repair($day);
            }else{
                $this->send_msg($day, $msg,$code);
                $this->dump($msg);
            }
            
        }
    }
    
    
    /**
     * 修复执行
     * 数据检查后发现有遗漏数据，进行再次补充数据的发送
     * 1.获取那一天的全部的dev_id数据集合发送给阿里云做差集处理,
     * 2.从考勤系统服务器返回遗漏的id，根据id，提取数据，发送打卡点
     * 3.考勤系统服务器接收保存打卡数据，从数据提取姓名，针对姓名进行数据重置
     * date:2017年10月12日
     * author: EK_熊
     */
    public function check_repair($day){
      //  $day = I('day',date('Y-m-d'));//需要修复的那一天
        $url_repair_diff = $this->url.'repair_diff';//检查打卡记录总数量接口方法
        $url_repair_add = $this->url.'repair_add';//接收打卡记录
        $msg = '';
        $ids = $this->model->check_ids($day);
        if (!$ids){
            $this->send_msg($day,'[修复失败]:ids读取失败~');
            exit();
        }
        
        $curl = new Curl();
        $this->dump('[修复开始]：请求获取差集数据');
        //1.发送当天的打卡机的全部id记录,获取差集数据
        $request_diff = $curl->post($url_repair_diff, ['ids'=>urlencode(json_encode($ids)),'dev_code'=>$this->prefix,'date'=>$day]);
        
        $diff = json_decode($request_diff,true);
        if (!$diff || $diff == 'null'){
              $msg = "自动修复出错，[系统服务器]获取不到差集数据，可能不存在遗漏数据";
              $this->dump($msg);
              $this->send_msg($day,$msg); 
              exit();
        }else{
            $this->dump("遗漏id:".$request_diff);
            $checkin = $this->model->getlist($diff,0,$this->prefix);
            $request_add = $curl->post($url_repair_add, ['data'=>urlencode(json_encode($checkin)),'date'=>$day,'dev_code'=>$this->prefix]);
            $this->dump("[修复结果]：".json_decode($request_add));
        }
        
        
    }
    
    /**
     * 发送日志记录
     * @param unknown $day
     * @param unknown $msg
     * @param number $code
     * date:2017年10月13日
     * author: EK_熊
     */
    public function send_msg($day,$msg,$code=0){
        $curl = new Curl();
        $url_post_result = $this->url.'total_prev_result';
        $ret = $curl->post($url_post_result, ['result'=>"[$day]$msg",'code'=>$code,'dev_code'=>$this->prefix]);
    }
    
    
    /**
     * 必须在使用命令行启动，不然浏览器崩溃
     * 
     * date:2017年9月11日
     * author: EK_熊
     */
    public function index(){
        $curl = new Curl();
        $this->dump('程序启动..');
        $last_request_id = 0;
        $url_config = $this->url.$this->act_config;
        $url_send = $this->url.$this->act_send;
        $url_ot_wx = $this->url.'overtime_alert';//加班微信提醒
        
        do{
            $request = $curl->get($url_config.'&dev_code='.$this->prefix);
            $request = json_decode($request,true);
            if (!$request){
                $this->dump("配置接收失败,程序停止！");
                $this->time_sleep(120);
                continue;
            }
            $limit = intval($request['limit']);
            $wait_time = intval($request['wait_time']);
            //先判断是否发送数据
            if ($limit > 0) {
                //查找数据
                
                $list = $this->model->getlist($request['last_id'],$request['limit'],$this->prefix);
                //抓取到的配置lastid 等于 我这边获取到的数据的lastid一致的话，就暂停发送
                $last_request_id = $list[count($list)-1]['dev_id'];
                
        
                
                if (empty($list)) {
                    $this->dump("没有最新数据可发送！");
                }else{
                    //整理打卡点数据，给没名字的数据，添加姓名
                    $list = $this->get_user_name($list);
                   //发送数据
                   $jsondata = json_encode($list,JSON_UNESCAPED_UNICODE);
                   $respon = json_decode($curl->post($url_send, ['data'=>$jsondata]),true);
                   
                   //异步访问加班问候接口,当天22:00 到第二天08:00之间触发
                   $start_time=date('Y-m-d 22:00:00');
                   $end_time = date('Y-m-d 08:00:00',strtotime("+1 day"));
                   $cur_time = date('Y-m-d H:i:s');
                   if ($cur_time >= $start_time && $cur_time <= $end_time){
                       $a = $curl->post($url_ot_wx, ['data'=>$jsondata]);
                   }
                   
                   
                   if (!$respon) {
                       $this->dump('发送失败,中断程序，休息60秒再重新连接...');
                       $this->time_sleep(60);
                       continue;
                   }
                   
                   if ($respon['errcode'] !== 0) {
                       $this->dump($respon['errmsg']);
                       $this->time_sleep($wait_time);
                       
                       continue;
                   }
//                    $this->dump($respon);
                   $this->dump($jsondata);//打印数据显示
                }
            }else{
                $this->dump('客户暂停接收数据，暂停获取数据！');
            }
            
            $this->time_sleep($wait_time);
        //获取配置
        }while(IS_CLI);
        
    }
    
    //获取用户信息,给没名字的数据添加姓名,避免姓名信息的缺失给考勤系统带来数据断层
    public function get_user_name($list){
        $curl = new Curl();
        $url = $this->api_user.'index.php?g=Home&m=Api&code=5885aeeda19e7&a=get_all_user_baseinfo';
        $snbox = [];
        foreach ($list as $k=>$v) {
            if (!$v['name']) $snbox[] = $v['sn'];
        }
        
        if ($snbox){
            $where['sn'] = ['in',$snbox];
            $request = $curl->post($url, ['where'=>urlencode(json_encode($where)),'field'=>'sn,ep_name']);
            $request = json_decode($request,true);
            if ($request['errcode'] !== 0){
                $this->dump('获取用户信息错误！');
            }else{
                $userInfo = $request['data'];
                foreach ($list as $k=>$v){
                    if (!$v['name']) $list[$k]['name'] = $userInfo[$v['sn']];
                }
            }
        }
        return $list;
    }
    
    
    public function time_sleep($wait_time){
        if (IS_CLI) {
            if ($wait_time <= 0) $wait_time = 60;
            $this->dump("休息 {$wait_time}秒...");
            sleep($wait_time);
        }
    }
    
    
    
    /**
     * 每半个小时，对比蓝波数据库和中控数据库，发现遗漏数据，直接发送给考勤数据库
     * 
     * date:2017年12月18日
     * author: EK_熊
     */
    public function checkAtten(){
        $User = M('Checkinout','','DB_ATT');
        $a = $User->where(['id'=>111578])->limit(4)->select();
        dump($a);
        
        $User = M('Checkinout');
        $a = $User->where(['id'=>111578])->limit(4)->select();
        dump($a);
    }
    
    
    
    
    
    
    
    
    /**
     * 信息输出
     * @param unknown $str
     * date:2017年9月12日
     * author: EK_熊
     */
    public function dump($str){
        if (IS_CLI) {
            echo iconv('UTF-8', 'GBK', $str)."\r\n";
        }else{
            dump($str);
        }
        
    }
    
    
    public function test(){
        $start_time=date('Y-m-d 07:00:00');
        $end_time = date('Y-m-d 08:00:00',strtotime("+1 day"));
        $cur_time = date('Y-m-d H:i:s');
        if ($cur_time >= $start_time && $cur_time <= $end_time){
//             $a = $curl->post($url_ot_wx, ['data'=>$jsondata]);
dump('1111');
        }
        
        exit();
        $jsondata = '[{"dev_id":"828944","sn":"0923","time":"2017-12-15 14:23:10","name":"魏圣平","dev_code":"fzzx_1","row_number":"1"},{"dev_id":"828945","sn":"10144","time":"2017-12-15 14:24:21","name":"黄安信","dev_code":"fzzx_2","row_number":"2"}]';
        
        $curl = new Curl();
        $this->domain = 'web.idea.3xy.me';
        $this->url = "http://$this->domain/insight20170117_attendance/index.php?g=&m=loader&a=";
        $url_ot_wx = $this->url.'overtime_alert';//加班微信提醒
        $a = $curl->post($url_ot_wx, ['data'=>$jsondata]);
        dump($a);
    }
    
    
    
    
    
    


    
}